<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" width="600px" destroyOnClose>
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, reactive } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { formSchema } from "./dataGroup.data"
  import { listDataGroupTree } from "/@/api/infra/dataGroup"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { isFunction } from "/@/utils/is"

  interface State {
    saveOrUpdateApi: Function
    groupType?: string
    isTree?: boolean
    bizType?: string | number
    groupCodeRequired?: boolean
  }
  const { createMessage } = useMessage()

  const emit = defineEmits(["register", "success"])
  const isUpdate = ref(true)
  const state = reactive<State>({
    saveOrUpdateApi: () => {},
  })

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    schemas: formSchema,
    labelWidth: 85,
    wrapperCol: {
      xs: { span: 20 },
      sm: { span: 20 },
    },
    showActionButtonGroup: false,
  })

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    state.groupType = data.groupTpe
    state.saveOrUpdateApi = data.saveOrUpdateApi
    state.isTree = data.isTree
    state.bizType = data.bizType
    state.groupCodeRequired = data.groupCodeRequired
    if (!isFunction(state.saveOrUpdateApi)) {
      console.log("data", data)
      createMessage.error("saveOrUpdateApi不是一个函数")
      closeModal()
      return
    }

    if (!state.bizType) {
      createMessage.error("bizType不能为空")
      closeModal()
      return
    }

    await resetFields()
    setModalProps({ confirmLoading: false, draggable: false, canFullscreen: false })
    isUpdate.value = !!data?.isUpdate
    //表单赋值
    await setFieldsValue({ isTree: state.isTree, ...data.record })
    if (state.isTree) {
      const treeData = await listDataGroupTree({ bizType: state.bizType, groupType: state.groupType })
      updateSchema([
        {
          field: "parentId",
          componentProps: ({ formModel, formActionType }) => {
            const parentId = formModel["parentId"]
            formModel["parentId"] = parentId === "0" || !parentId ? undefined : parentId
            return {
              treeData,
              fieldNames: {
                title: "name",
                key: "id",
                value: "id",
              },
              dropdownStyle: {
                maxHeight: "60vh",
              },
              showSearch: true,
              allowClear: true,
              getPopupContainer: (node) => node.parentNode,
            }
          },
        },
      ])
    }
    updateSchema([
      {
        field: "code",
        required: state.groupCodeRequired,
      },
    ])
  })

  const title = computed(() => (!unref(isUpdate) ? "新增" : "编辑"))
  async function handleSubmit(v) {
    try {
      let values = await validate()
      setModalProps({ confirmLoading: true })
      await state.saveOrUpdateApi({ ...values, groupType: state.groupType }, isUpdate.value)
      closeModal()
      emit("success")
      createMessage.success(`${title.value}分组成功`)
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
